<?
/*###########################<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

文件:mysql.inc.php
用途:MYSQL類
作者:是夢的(dreamxyp)[QQ31996798]
更新:2007.7.10

#############################<meta http-equiv="Content-Type" content="text/html; charset=utf-8">*/
class db
{
    protected $_config = array(
    		 		'host' 		=> '127.0.0.1',
        			'database' => null,
        			'username' => null,
        			'password' => null
        		);
   	#@ class cache
    protected $_rs;
    protected $_conn; 		//_connection
    protected $_sql;
    protected $_insertId;
    protected $_queryTimes;
	protected $_queryAffected;
	#db charset
	protected $_charset		= 'utf8';//,'utf8','gbk',latin1;
	#db select 
	static public $_select_db;
    /*	*******************
    	  Function
    	******************* */
    public function __construct($config,$charset=false)
    {
        $charset && $this->_charset = $charset;
		$this->_config = $config;
    	$this->_conn = mysql_connect(
										$this->_config['host'] , 
										$this->_config['username'], 
										$this->_config['password'], 
										0, 
										MYSQL_CLIENT_IGNORE_SPACE
									) or die("DateBase Err: " . mysql_errno() . ": " . mysql_error() );
		$this->__select_db();	
	}
    protected function __select_db()
    {
        if(self::$_select_db != $this->_config['database'])
        {
	        mysql_select_db($this->_config['database'], $this->_conn);
			if(function_exists("mysql_set_charset"))
			{
				mysql_set_charset($this->_charset, $this->_conn);
			}else
			{
				mysql_query("SET NAMES ".$this->_charset, $this->_conn);
			}
			self::$_select_db = $this->_config['database'];
        }
    }
    protected function format($sql, $bind)
    {
    	if($bind)
		{
			return strstr($sql, "?")?$this->quoteInto($sql, $bind):$this->bindValue($sql, $bind);
		}else
		{
			return $sql;
		}
    }
    protected function bindValue($sql, $bind)
    {
        $rs =preg_split("/(\:[A-Za-z0-9_]+)\b/",$sql, -1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
        foreach ($rs as &$v)  $v[0] == ':' && $v = $this->quote($bind[substr($v, 1)]);
        return implode('', $rs);
    }
    //======================================
    // 函數: quoteInto()
    // 功能: 定位
    // 參數: @$text string
    //	     @$value  string
    // 返回: sql string
    //======================================
    protected function quoteInto($text, $value)
    {
        return str_replace('?', $this->quote($value), $text);
    }
    //======================================
    // 函數: quote()
    // 功能: 添加引號防止數據庫攻擊
    // 參數: string
    // 返回: mysql_real_escape_string
    //======================================
    protected  function quote($value)
    {
        if (is_array($value))
        {
            foreach ($value as & $val)
            {
                $val = $this->quote($val);
            }
            return implode(', ', $value);
        } else
        {
            return "'" . mysql_real_escape_string($value) . "'";
        }
    }
    /*	********************************************************
    	 **	公共函數庫
    	******************************************************** */
    //======================================
    // 函數: conn()
    // 功能: query
    // 參數: @$sql string
    //	     @$bind  string|array
    // 返回: MYSQL句柄
    //======================================
    public function conn($sql, $bind='')
    {
        $this->__select_db();
        $sql && $this->_sql 	= $this->format($sql, $bind);
        //mysql_pconnect
        $this->_rs 				= mysql_query($this->_sql, $this->_conn);
        $this->_queryTimes++;
        return $this->_rs;
    }
    //======================================
    // 函數: insert()
    // 功能: 插入一條記錄
    // 參數: @$table 表名
    //	     @$bind  array
    // 返回: 本條記錄的
    //======================================
    public function insert($table,$bind,$ext='')
    {
        // Check for associative array
        if (array_keys($bind) !== range(0, count($bind) - 1)) 
        {
            // Associative array
           $cols = array_keys($bind);
	       $sql = "INSERT INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (:' . implode(', :', $cols) . ') '.$ext;
	       $this->conn($sql, $bind);
        } else 
        {
            // Indexed array
            $tmpArray = array();
            $cols = array_keys($bind[0]);
            foreach($bind as $v)
            {
                $tmpArray[] = $this->format(' :' . implode(', :', $cols) . ' ',$v);
            }
            $sql = "INSERT INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (' . implode('),(', $tmpArray) . ') '.$ext;
	        $this->conn($sql);
        }
		$this->_insertId 		= mysql_insert_id($this->_conn);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
    	return $this->_insertId;
    }
    //======================================
    // 函數: inserts()一次有多個時用這個
    // 功能: 插入一條記錄
    // 參數: @$table 表名
    //	     @$bind  array
    // 返回: 本條記錄的IDDELAYED
    //======================================
    public function inserts($table, $bind,$ext)
    {
        // Check for associative array
        if (array_keys($bind) !== range(0, count($bind) - 1)) 
        {
            // Associative array
           $cols = array_keys($bind);
	       $sql = "INSERT DELAYED INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (:' . implode(', :', $cols) . ') ';
	       $this->conn($sql, $bind);
        } else 
        {
            // Indexed array
            $tmpArray = array();
            $cols = array_keys($bind[0]);
            foreach($bind as $v)
            {
                $tmpArray[] = $this->format(' :' . implode(', :', $cols) . ' ',$v);
            }
            $sql = "INSERT DELAYED INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (' . implode('),(', $tmpArray) . ') ';
	        $this->conn($sql);
        }
		$this->_insertId 		= mysql_insert_id($this->_conn);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_insertId;
    }
    //======================================
    // 函數: REPLACE()
    // 功能: 插入一條記錄
    // 參數: @$table 表名
    //	     @$bind  array
    // 返回: 本條記錄的ID
    //======================================
    public function replace($table, $bind)
    {
        // Check for associative array
        if (array_keys($bind) !== range(0, count($bind) - 1)) 
        {
            // Associative array
           $cols = array_keys($bind);
	       $sql = "REPLACE INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (:' . implode(', :', $cols) . ') ';
	       $this->conn($sql, $bind);
        } else 
        {
            // Indexed array
            $this->_connect('u');
            $tmpArray = array();
            $cols = array_keys($bind[0]);
            foreach($bind as $v)
            {
                $tmpArray[] = $this->format(' :' . implode(', :', $cols) . ' ',$v);
            }
            $sql = "REPLACE INTO $table " . '(`' . implode('`, `', $cols) . '`) ' . 'VALUES (' . implode('),(', $tmpArray) . ') ';
	        $this->conn($sql);
        }
		$this->_insertId 		= mysql_insert_id($this->_conn);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_insertId;
    }
    //    ======================================
    // 函數: update()
    // 功能: 數椐更新
    // 參數: @$table 表名
    //	     @$bind  array
    //       @$where 條件 
    // 返回: 無
    //======================================
    public function update($table, $data, $where ='',$bind = '')
    {
        $where && $where = $this->format($where,$bind);
    	$set = array ();
        foreach ($data as $col => $val)
        {
            $set[] = "`$col` = :$col";
        }
        $sql = "UPDATE `{$table}` " . 'SET ' . implode(', ', $set) . (($where) ? " WHERE {$where}" : '');
        $this->conn($sql, $data);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_queryAffected;
    }
	//    ======================================
    // 函數: adddate()
    // 功能: 數椐疊加
    // 參數: @$table 表名
    //	     @$bind  array
    //       @$where 條件 
    // 返回: 無
    //======================================
    public function add($table, $data, $where ='',$bind = '')
    {
        $where && $where = $this->format($where,$bind);
    	$set = array ();
        foreach ($data as $col => $val)
        {
            $set[] = "`$col` = $col + ".(float)$val;
        }
        $sql = "UPDATE `{$table}` " . 'SET ' . implode(', ', $set) . (($where) ? " WHERE {$where}" : '');
        $this->conn($sql);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_queryAffected;
    }
	//    ======================================
    // 函數: cutdate()
    // 功能: 數椐疊加
    // 參數: @$table 表名
    //	     @$bind  array
    //       @$where 條件 
    // 返回: 無
    //========================================
    
    public function cut($table, $data, $where = '',$bind = '')
    {
        $where && $where = $this->format($where,$bind);
    	$set = array ();
        foreach ($data as $col => $val)
        {
            $set[] = "`$col` = $col - ".(float)$val;
        }
        $sql = "UPDATE `{$table}` " . 'SET ' . implode(', ', $set) . (($where) ? " WHERE {$where}" : '');
        $this->conn($sql);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_queryAffected;
    }
    //======================================
    // 函數: delete()
    // 功能: 刪除記錄
    // 參數: @$table 表名
    //	     @$where 條件 
    // 返回: 無
    //======================================
    public function delete($table, $where = false,$bind='')
    {
        $sql = "DELETE FROM $table" . (($where) ? " WHERE $where" : '');
        $this->conn($sql,$bind);
		$this->_queryAffected   = mysql_affected_rows($this->_conn);
		return $this->_queryAffected;
    }
    //======================================
    // 函數: rsCount()
    // 功能: 得到數椐的行數
    // 參數: @$sql 
    // 返回: int
    //======================================
    public function rows($sql = '', $bind = '')
    {
        $sql && $this->conn($sql, $bind);
        if($this->_rs)
		{
			return  mysql_num_rows($this->_rs);
		}else
		{
			return false;
		}
    }
	public function rsCount($sql = '', $bind = '')
    {
        return $this->rows($sql, $bind);
    }
    //======================================
    // 函數: rsArray()
    // 功能: 得到數椐數組
    // 參數: @$sql 
    // 返回: array
    //======================================
	public function row($sql = '', $bind = '')
    {
        $sql && $this->conn($sql, $bind);
		if($this->_rs)
		{
			return mysql_fetch_assoc($this->_rs);
		}else
		{
			return false;
		}
    }
    public function rsArray($sql = '', $bind = '')
    {
        return $this->row($sql, $bind);
    }
    //======================================
    // 函數: dateArray() fetchAll()
    // 功能: 得到數椐數組
    // 參數: @$sql 
    // 返回: array
    //======================================
    public function dataArray($sql = '', $bind = '')
    {
        $rs = array();
		$this->rows($sql,$bind);
		while ($rss = &$this->row())
			$rs[] = $rss;
		$this->free();
        return $rs;
    }
    public function fetchAll($sql = '', $bind = '')
    {
    	return $this->dataArray($sql, $bind);
    }
	
    public function fetchAssoc($sql = '', $bind = '',$keyField='')
    {
        $rs = array();
		$this->rows($sql,$bind);
		if($keyField)
		{
		   while ($rss = &$this->row())
		   		$rs[$rss[0]] = $rss; 
		}else
		{
			while ($rss = &$this->row()) 
			{
				$tmp = array_values($rss);
				$rs[$tmp[0]] = $rss;
			}
		}
		$this->free();
        return $rs;
	}
    //======================================
    // 函數: rowRepeat()
    // 功能: 返回某個欄位元的內容是否重複
    // 參數: @$sql 
    // 返回: 有返回true 沒有為false
    //======================================
    public function rowRepeat($table, $row, $msg) //,λԪ,
    {
        if ($table && $row && $msg)
        {
            $row = $this->row("select count(" . $row . ") as c from " . $table . " where " . $row . " = ? ",$msg);
            return $row['c']?true:false;
        }
        return false;
    }
    //======================================
    // 函數: insertID()
    // 功能: 返回最後一次插入的自增ID
    // 參數: 無
    //======================================
    public function insertID()
    {
        return $this->_insertId;
    }
    //======================================
    // 函數: queryTimes()
    // 功能: 返回查詢的次數
    // 參數: 無
    // 返回: 查詢的次數
    //======================================
    public function queryTimes()
    {
        return $this->_queryTimes;
    }
    public function getSql()
    {
        return $this->_sql;
    }
	public function affected()
    {
        return $this->_queryAffected;
    }
    public function free()
    {
        if(is_resource ($this->_rs))
        	return mysql_free_result($this->_rs);
        return false;
    }
    //======================================
    // 函數: close()
    // 功能: 關閉打開的連接
    // 參數: 無
    // 返回: 無
    //======================================
    public function close()
    {
        $this->_conn && mysql_close($this->_conn);
    }
} //end class
?>
